package com.lyy.weather.fragment;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.lyy.weather.R;
import com.lyy.weather.TIme.TimeUtil;
import com.lyy.weather.activity.MainActivity;
import com.lyy.weather.bean.AirIndices;
import com.lyy.weather.bean.City;
import com.lyy.weather.bean.LifeIndices;
import com.lyy.weather.bean.RefreshableView;
import com.lyy.weather.bean.ThreadFlag;
import com.lyy.weather.bean.WeatherDaily;
import com.lyy.weather.bean.WeatherHourly;
import com.lyy.weather.bean.WeatherTimely;
import com.lyy.weather.database.DatabaHelper;
import com.lyy.weather.database.DatabaseUtil;
import com.lyy.weather.layout.adapter.WholeAdapter;
import com.lyy.weather.layout.bean.AirIndicesItem4;
import com.lyy.weather.layout.bean.LifeIndicesItem5;
import com.lyy.weather.layout.bean.MainItem;
import com.lyy.weather.layout.bean.RecyclerItem2;
import com.lyy.weather.layout.bean.RecyclerItem3;
import com.lyy.weather.layout.bean.Type;
import com.lyy.weather.layout.bean.WeatherDailyItem3;
import com.lyy.weather.layout.bean.WeatherHourlyItem2;
import com.lyy.weather.network.HttpUtil;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class WeatherFragment extends Fragment {
    private DatabaHelper dbHelper;
    private String DEFAULT_CITY="101280101";//默认城市为广州
    private DatabaseUtil databaseUtil;
    private WholeAdapter wholeAdapter;

    //展示天气的各子项类及表
    private MainItem item1;
    private RecyclerItem2 item2;
    private RecyclerItem3 item3;
    private AirIndicesItem4 item4;
    private LifeIndicesItem5 item5;
    private ThreadFlag threadFlag;
    private List<WeatherHourlyItem2> weatherHourlyItem2List;
    private List<WeatherDailyItem3> weatherDailyItem3List;
    private List<Type> itemList;
    private String locationId;
    private MainActivity activity;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
       View view=inflater.inflate(R.layout.weather_fragment,container,false);
       return view;
    }

    public MainItem setDataInMainItem(String locationId){
        City city=(City) databaseUtil.searchCity(locationId);
        WeatherTimely weatherTimely=(WeatherTimely)databaseUtil.searchWeatherTimely(locationId);
        List<WeatherDaily> weatherDailyList=databaseUtil.searchWeatherDaily(locationId);
        AirIndices airIndices=(AirIndices)databaseUtil.searchAirIndices(locationId);
        //LayoutUtil layoutUtil=new LayoutUtil(databaseUtil,"101280101");
        MainItem mainItem=new MainItem();
        mainItem.setCity(city.getName());
        mainItem.setTempMaxAndMin(weatherDailyList.get(0).getTempMax()+"/"+
                weatherDailyList.get(0).getTempMin()+"℃");
        mainItem.setTemperature(weatherTimely.getTemp());
        mainItem.setAirCategory(airIndices.getCategory());
        return mainItem;
    }



    private SwipeRefreshLayout refreshLayout;
    public List<WeatherHourlyItem2> setDataInItem2(String locationId){
        // TimeUtil timeUtil=new TimeUtil();
        List<WeatherHourly> hourlyList=databaseUtil.searchWeatherHourly(locationId);
        Iterator<WeatherHourly> it=hourlyList.iterator();
        List<WeatherHourlyItem2> item2List=new ArrayList<>();//要返回的表
        while(it.hasNext()){
            WeatherHourly hourly=it.next();
            WeatherHourlyItem2 item2=new WeatherHourlyItem2();
            item2.setPicId(hourly.getIcon());
            item2.setTemperature(hourly.getTemp()+"℃");

            Date date= null;
            try {
                date = TimeUtil.getDateInFormat(hourly.getFxTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String time=TimeUtil.getHourlyString(date);
            item2.setTime(time);
            item2List.add(item2);
        }
        return item2List;
    }
    public List<WeatherDailyItem3> setDataInItem3(String locationId){
        List<WeatherDaily> dailyList=databaseUtil.searchWeatherDaily(locationId);
        Iterator<WeatherDaily> it=dailyList.iterator();
        List<WeatherDailyItem3> item3List=new ArrayList<>();//要返回的表
        while ((it.hasNext())){
            WeatherDaily daily=it.next();
            WeatherDailyItem3 item3=new WeatherDailyItem3();
            item3.setPicId(daily.getIconDay());
            item3.setTempMax(daily.getTempMax());
            item3.setTempMin(daily.getTempMin());
            item3.setWeatherText(daily.getTextDay());

            item3.setDate(daily.getFxDate());
            item3List.add(item3);
        }
        return item3List;
    }
    public AirIndicesItem4 setDataInItem4(String locationId){
        AirIndices airIndices=(AirIndices)databaseUtil.searchAirIndices(locationId);
        AirIndicesItem4 item4=new AirIndicesItem4();//要返回的值
        item4.setAqi(airIndices.getAqi());
        item4.setCategory(airIndices.getCategory());
        item4.setCo(airIndices.getCo());
        item4.setNo2(airIndices.getNo2());
        item4.setSo2(airIndices.getSo2());
        item4.setO3(airIndices.getO3());
        item4.setPm2p5(airIndices.getPm2p5());
        item4.setPm10(airIndices.getPm10());

        return item4;
    }
    public LifeIndicesItem5 setDataInItem5(String locationId){
        LifeIndices lifeIndices=(LifeIndices)databaseUtil.searchLifeIndices(locationId);
        List<LifeIndices.DifferentIndices> indicesList=lifeIndices.getIndicesList();
        LifeIndicesItem5 item5=new LifeIndicesItem5();//要返回的值
        Iterator<LifeIndices.DifferentIndices> it=indicesList.iterator();
        while(it.hasNext()){
            LifeIndices.DifferentIndices differentIndices=it.next();
            switch (differentIndices.getType()){
                case 1:
                    item5.setSport(differentIndices.getCategory());
                    break;
                case 3:
                    item5.setDressing(differentIndices.getCategory());
                    break;
                case 4:
                    item5.setFishing(differentIndices.getCategory());
                    break;
                case 5:
                    item5.setUv(differentIndices.getCategory());
                    break;
                case 6:
                    item5.setJourney(differentIndices.getCategory());
                    break;
                case 7:
                    item5.setPollen(differentIndices.getCategory());
                    break;
                case 8:
                    item5.setComfort(differentIndices.getCategory());
                    break;
                case 9:
                    item5.setGetCold(differentIndices.getCategory());
                    break;
                case 10:
                    item5.setAirPollution(differentIndices.getCategory());
                    break;
                case 11:
                    item5.setAirConditionor(differentIndices.getCategory());
                    break;
                case 12:
                    item5.setSunglass(differentIndices.getCategory());
                    break;
                case 13:
                    item5.setMakeup(differentIndices.getCategory());
                    break;

            }

        }
        return item5;
    }
    private void showWeather(String locationId){

        //调试用，组装子项数据
        WeatherHourlyItem2 weatherHourlyItem2=new WeatherHourlyItem2();
        WeatherDailyItem3 weatherDailyItem3=new WeatherDailyItem3();
        //运行起main RecyclerView
        //组装数据
        weatherHourlyItem2List=new ArrayList<>();
        weatherHourlyItem2List=setDataInItem2(locationId);

        weatherDailyItem3List=new ArrayList<>();
        weatherDailyItem3List=setDataInItem3(locationId);

        //获取子项数据
        item1=new MainItem();
        item1=setDataInMainItem(locationId);

        item2=new RecyclerItem2(weatherHourlyItem2List);
        item3=new RecyclerItem3(weatherDailyItem3List);
        item4=new AirIndicesItem4();
        item4=setDataInItem4(locationId);
        item5=new LifeIndicesItem5();
        item5=setDataInItem5(locationId);

        //装到表里~
        itemList=new ArrayList<>();
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        itemList.add(item5);

        ListView recyclerView=(ListView)activity.findViewById(R.id.main_list_view);
        //LayoutManager用于指定RecyclerView的布局方式，这里使用的是线性布局，可以实现和ListView类似的效果
       // LinearLayoutManager layoutManager=new LinearLayoutManager();
        // recyclerView.setLayoutManager(layoutManager);
        //创建适配器实例，将子项数据传入
        WholeAdapter wholeAdapter=new WholeAdapter(activity,itemList,databaseUtil,dbHelper);
        //设置适配器，完成关联
        recyclerView.setAdapter(wholeAdapter);
        /**/

        String nowLocationId=activity.getNowLocationId();
        refreshLayout=(SwipeRefreshLayout)activity.findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //先更新当前城市的数据库
                //先删除
                databaseUtil.deleteLocationIdInfo(nowLocationId);
                //再添加
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpUtil httpUtil = new HttpUtil(nowLocationId, HttpUtil.MyRequestType.ALL_DATA_REQUEST, databaseUtil.getmContext(),
                                databaseUtil.getDbHelper());
                        httpUtil.getDataFromApi();
                        //更换新碎片
                       /* runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                activity.replaceFragment(new WeatherFragment());
                                refreshLayout.setRefreshing(false);
                                Toast.makeText(activity, "刷新成功~", Toast.LENGTH_SHORT).show();
                            }
                        });
                        */
                        activity.replaceFragment(new WeatherFragment());
                        refreshLayout.setRefreshing(false);


                    }
                }).start();

                Toast.makeText(activity, "刷新成功~", Toast.LENGTH_SHORT).show();
            }

        });
        refreshLayout.setProgressViewOffset(true, -0, 100);
        refreshLayout.setOnChildScrollUpCallback(null);


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
     //  RefreshableView refreshableView=(RefreshableView)getActivity().findViewById(R.id.refreshable_view);
        dbHelper = new DatabaHelper(getActivity(), "WeatherInformation.db", null, 31);
        // dbHelper.getWritableDatabase();
        databaseUtil = new DatabaseUtil(getActivity(),dbHelper);
        SQLiteDatabase db=dbHelper.getReadableDatabase();

        activity=(MainActivity)getActivity();
        locationId=activity.getNowLocationId();
        showWeather(locationId);


    }
}
